package com.example.wangning.mycarofcountry.my;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.base.BaseApplication;
import com.example.wangning.mycarofcountry.login.LoginActivity;
import com.example.wangning.mycarofcountry.tool.Constants;
import com.example.wangning.mycarofcountry.tool.DayNightMode;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.Map;

public class MyFragment extends Fragment {
    // 整个平台的Controller,负责管理整个SDK的配置、操作等处理
    private UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constants.DESCRIPTOR);
    private ImageButton imageButton_moon;
    private TextView personNameLogin_Tv,person_loginTv,personQQLogin_Tv,personWeiBoLogin_Tv,share_Tv;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person_login,null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        imageButton_moon = (ImageButton) view.findViewById(R.id.imgBtn);
        personNameLogin_Tv = (TextView) view.findViewById(R.id.personNameLogin_Tv);
        person_loginTv = (TextView) view.findViewById(R.id.person_loginTv);
        personWeiBoLogin_Tv = (TextView) view.findViewById(R.id.personWeiBoLogin_Tv);
        personQQLogin_Tv = (TextView) view.findViewById(R.id.personQQLogin_Tv);
        share_Tv = (TextView) view.findViewById(R.id.share_Tv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 配置需要分享的相关平台
        configPlatforms();
        // 设置分享的内容
        setShareContent();
        imageButton_moon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int theme = DayNightMode.getDayNightMode(getActivity());
                switch (v.getId()) {
                    case R.id.imgBtn:
                        if (theme == DayNightMode.THEME_SUN) {
                            DayNightMode.setDayNightMode(getActivity(), DayNightMode.THEME_NIGHT);
                        } else {
                            DayNightMode.setDayNightMode(getActivity(), DayNightMode.THEME_SUN);
                        }
                        // 注意改过主题后一定要，把activity finish在重开一遍，因为更改主题只能在oncreat中进行
                        getActivity().finish();
                        getActivity().startActivity(new Intent(getActivity(), getActivity().getClass()));
                        break;
                }
            }
        });
        personNameLogin_Tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 100);
            }
        });
        person_loginTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 100);
            }
        });
        personQQLogin_Tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(SHARE_MEDIA.QQ);
            }
        });
        personWeiBoLogin_Tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(SHARE_MEDIA.SINA);
            }
        });
        share_Tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCustomPlatforms();
            }
        });

    }

    /**
     * 配置分享平台参数
     */
    private void setShareContent() {
// 添加新浪sso授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        // 添加QQ、QZone平台
        addQQQZonePlatform();
        // 添加微信、微信朋友圈平台
    }

    private void addQQQZonePlatform() {
        String appId = "100424468";
        String appKey = "c7394704798a158208a74ab60104f0ba";
        // 添加QQ支持, 并且设置QQ分享内容的target url
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(getActivity(),
                appId, appKey);
        qqSsoHandler.setTargetUrl("http://www.umeng.com");
        qqSsoHandler.addToSocialSDK();
        // 添加QZone平台
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(
                getActivity(), appId, appKey);
        qZoneSsoHandler.addToSocialSDK();

    }

    private void configPlatforms() {
        // 配置SSO
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(
                getActivity(), "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
        mController.setShareContent("友盟社会化组件（SDK）让移动应用快速整合社交分享功能");
        // 设置QQ空间分享内容
        QZoneShareContent qzone = new QZoneShareContent();
        qzone.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能 -- QZone");
        UMImage localImage = new UMImage(getActivity(), R.mipmap.device);
        UMImage urlImage = new UMImage(getActivity(),
                "http://www.umeng.com/images/pic/social/integrated_3.png");
        qzone.setTargetUrl("http://www.umeng.com/social");
        qzone.setTitle("QZone title");
        qzone.setShareImage(urlImage);
        mController.setShareMedia(qzone);
        SinaShareContent sinaContent = new SinaShareContent(urlImage);
        sinaContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能，新浪微博");
        mController.setShareMedia(sinaContent);
    }
    /**
     * 添加所有的平台</br>
     */
    private void addCustomPlatforms() {

        // 添加QQ平台
        addQQQZonePlatform();
        mController.getConfig().setPlatforms(
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
                SHARE_MEDIA.SINA);
        mController.openShare(getActivity(), false);
    }
    /**
     * @功能描述 : 添加QQ平台支持 QQ分享的内容， 包含四种类型， 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
     *       image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
     *       要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
     *       : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
     * @return
     */
    /**
     * 授权。如果授权成功，则获取用户信息
     *
     * @param platform
     */
    private void login(final SHARE_MEDIA platform) {
        mController.doOauthVerify(getActivity(), platform,
                new SocializeListeners.UMAuthListener() {

                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                        Toast.makeText(getActivity(), "授权开始",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SocializeException e,
                                        SHARE_MEDIA platform) {
                        Toast.makeText(getActivity(), "授权失败",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        // 获取uid
                        String uid = value.getString("uid");
                        if (!TextUtils.isEmpty(uid)) {
                            // uid不为空，获取用户信息
                            getUserInfo(platform);
                        } else {
                            Toast.makeText(getActivity(), "授权失败...",
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                        Toast.makeText(getActivity(), "授权取消",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }
    /**
     * 获取用户信息
     *
     * @param platform
     */
    private void getUserInfo(SHARE_MEDIA platform) {
        mController.getPlatformInfo(getActivity(), platform,
                new SocializeListeners.UMDataListener() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        // String showText = "";
                        // if (status == StatusCode.ST_CODE_SUCCESSED) {
                        // showText = "用户名：" +
                        // info.get("screen_name").toString();
                        // Log.d("#########", "##########" + info.toString());
                        // } else {
                        // showText = "获取用户信息失败";
                        // }

                        if (info != null) {
                            Toast.makeText(getActivity(), info.toString(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
    // 如果有使用任一平台的SSO授权, 则必须在对应的activity中实现onActivityResult方法, 并添加如下代码
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 根据requestCode获取对应的SsoHandler
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
                resultCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if (requestCode == 100 && resultCode == 200){
            if (data != null){
                person_loginTv.setText("尊敬的:" + data.getStringExtra("loginName") + ",欢迎您");
            }

        }
    }
}
